package stat;

import com.xeiam.xchart.Chart;
import com.xeiam.xchart.StyleManager;
import com.xeiam.xchart.XChartPanel;
import tsd.TSD;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Author: Oleg Yasnev (oyasnev@gmail.com)
 * Date: 23.05.14
 */
abstract public class TSDStatChart implements Observer {

    // Chart params
    public int locX, locY;
    public String chartHeader = "Chart header";
    public String chartTitle  = "Chart title";
    public String xTitle      = "X title";
    public String yTitle      = "Y title";
    public String seriesName  = "Series name";
    public int    chartWidth  = 500;
    public int    chartHeight = 400;

    protected ArrayList<Double> xData, yData;

    protected JFrame frame;
    protected XChartPanel chartPanel;

    protected boolean isChartBuild;

    public TSDStatChart(int locX, int locY) {
        this.locX = locX;
        this.locY = locY;

        xData = new ArrayList<Double>();
        yData = new ArrayList<Double>();
        isChartBuild = false;
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof TSDStat) {
            TSDStat tsdStat = (TSDStat) o;
            updateData(tsdStat.tsdList);
            if (isChartBuild) {
                updateChart();
            } else {
                buildChart();
            }
        }
    }

    public void close() {
        frame.dispose();
    }

    protected void updateData(List<TSD> tsdList) {

    }

    protected void updateChart() {
        if (xData.size() == 0) {
            xData.add(0.0);
            yData.add(0.0);
        }
        chartPanel.updateSeries(seriesName, xData, yData);
    }

    protected void buildChart() {
        chartPanel = new XChartPanel(getChart());
        isChartBuild = true;

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Create and set up the window.
                frame = new JFrame(chartHeader);
                frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
                frame.add(chartPanel);

                // Display the window.
                frame.pack();
                frame.setLocation(locX, locY);
                frame.setVisible(true);
            }
        });
    }

    protected Chart getChart() {
        // Create Chart
        Chart chart = new Chart(chartWidth, chartHeight);
        chart.setChartTitle(chartTitle);
        chart.setXAxisTitle(xTitle);
        chart.setYAxisTitle(yTitle);
        chart.getStyleManager().setLegendPosition(StyleManager.LegendPosition.InsideNE);
        chart.addSeries(seriesName, xData, yData);
        return chart;
    }
}
